package com.beerbook;

import java.io.File;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.ListView;
import android.widget.Spinner;

public class BeerbookActivity extends ListActivity implements OnClickListener {

	protected EditText searchText;
	protected SQLiteDatabase db;
	protected Cursor cursor;
	protected ListAdapter adapter;
	
	private String sortValue;
	private int sortPos;

    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
	    View addBeer = findViewById(R.id.AddBeer);
	    addBeer.setOnClickListener(this);
	    searchText = (EditText)findViewById(R.id.searchText);
	    searchText.addTextChangedListener(new TextWatcher() {
	        public void onTextChanged(CharSequence s, int start, int before, int count) {}
	        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

	        public void afterTextChanged(Editable s) {
	            showList();
	        }
	    });
	    
	    sortValue="Name";
	    sortPos=0;
	    searchText.setText("");
	    
	    Spinner spinner = (Spinner) findViewById(R.id.SpinnerSort);
	    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
	            this, R.array.sort_by_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
	    spinner.setSelection(sortPos);
        
        //Check SD card for correct folder
        File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/beerbook");
        if(!(f.exists()&&f.isDirectory())) {
        	System.out.println(Environment.DIRECTORY_PICTURES+"/beerbook" + " doesn't exist, Creating!");
        	f.mkdirs();
        } else {
        	System.out.println(Environment.DIRECTORY_PICTURES+"/beerbook" + " exists!");
        }
        
        showList();
    }
    
    public void showList(){
    	String sortOrder="";
    	if(sortValue.equals("Rating"))
    		sortOrder = " DESC";
    	
        db = (new BeerDB(this)).getWritableDatabase();
    	cursor = db.rawQuery("SELECT _id, name, brewery FROM beer WHERE name || ' ' || brewery LIKE ? ORDER BY " + sortValue + sortOrder, 
				new String[]{"%" + searchText.getText().toString() + "%"});
		adapter = new SimpleCursorAdapter(
				this, 
				R.layout.beer_list_item, 
				cursor, 
				new String[] {"name", "brewery"}, 
				new int[] {R.id.name, R.id.brewery});
		setListAdapter(adapter);
	    
	    db.close();
    }
    
    public void onResume(){
 		super.onResume();
 		showList();
    }
  
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.AddBeer:
			startActivity(new Intent(this, AddABeer.class));
			break;
		}
	}
    
    public void onListItemClick(ListView parent, View view, int position, long id) {
    	Intent intent = new Intent(this, BeerDetails.class);
    	Cursor cursor = (Cursor) adapter.getItem(position);
    	intent.putExtra("BEER_ID", cursor.getInt(cursor.getColumnIndex("_id")));
    	startActivity(intent);
    }
    
    public void search(View view) {
    	showList();
    }
    
    public class MyOnItemSelectedListener implements OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        	sortValue = parent.getItemAtPosition(pos).toString();
        	sortPos = pos;
        	showList();
        }
        public void onNothingSelected(AdapterView<?> parent) {
        	// Do nothing.
        }
    }
    
}